import { Product, ProductService, Comment } from './../shared/product.service';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { WebsocketService } from '../shared/websocket.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-product-detail',
  templateUrl: './product-detail.component.html',
  styleUrls: ['./product-detail.component.css']
})
export class ProductDetailComponent implements OnInit {

  isWatched: boolean = false;

  currentBid: number;

  isCommentHidden: boolean = true;
  product: Product;

  comments: Comment[];

  newRating: number = 5;

  newComment: string = '';

  subscription: Subscription;

  constructor(private routeInfo: ActivatedRoute,
    private productService: ProductService,
    private wsService: WebsocketService
  ) { }

  ngOnInit() {
    let productId: number = this.routeInfo.snapshot.params['productId'];
    this.productService.getProduct(productId).subscribe(product => {
      this.product = product;
      this.currentBid = product.price;
    });
    this.productService.getCommentsForProductId(productId).subscribe(comments => this.comments = comments);
  }
  addComment() {
    let comment: Comment = new Comment(0, this.product.id, new Date().toISOString(), 'someone',
      this.newRating, this.newComment);
      this.resetForm();
    this.comments.unshift(comment);
    let sum = this.comments.reduce((sum, comment) => sum + comment.rating, 0);
    this.product.rating = sum / this.comments.length;
  }
  resetForm() {
    this.newRating = 5;
    this.newComment = null;
    this.isCommentHidden = true;
  }

  watchProduct() {
    if (this.subscription) {
      this.subscription.unsubscribe();
      this.isWatched = false;
      this.subscription = null;
      return;
    } else {
      this.isWatched = true;
    }
    this.subscription = this.wsService.createObservableSocket('ws://localhost:8085', this.product.id)
      .subscribe(products => {
        let product = products.find(p => p.productId === this.product.id);
        this.currentBid = product.bid;
      });
  }
}
